package com.giser.testapp.lib.Location;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.content.ContextCompat;

import com.google.gson.Gson;
import com.giser.testapp.MainActivity;
import com.giser.testapp.lib.App.EnvApplication;
import com.giser.testapp.lib.App.GlobClass;
import com.giser.testapp.lib.Tool.AlertUtil;
import com.giser.testapp.lib.Tool.EnvLog;
import com.giser.testapp.lib.Tool.PhoneStateUtil;
import com.giser.testapp.lib.Tool.SystemSettingUtil;
import com.giser.testapp.lib.Tool.ToastUtil;

import java.util.Iterator;

import static com.giser.testapp.lib.App.GlobClass.LocationModule_NetWork_CODE;

/**
 * Created by Lss on 2017/12/11.
 */

public class LocationServer
{
    private LocationManager locationManager = null;
    private AndroidLocation androidLocation=null;
    private Context mContext=null;
    private AMapLocationServer aMapLocationServer=null;

    private long locationTime_GPS=5000;
    private float locationDistance_GPS=0;
    private int flag=0;
    public LocationServer(Context context){
        mContext=context;
        locationManager=(LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        androidLocation=new AndroidLocation();
        aMapLocationServer=new AMapLocationServer();
    }

    public void updateGpsSetting(){
        EnvLog.i("updateGpsSetting ................");
        if(ContextCompat.checkSelfPermission(mContext,android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
            if(locationManager!=null && androidLocation!=null){
                if(PhoneStateUtil.isGpsProviderEnabled(mContext)){
                    EnvLog.i("updateGpsSetting GpsProvider");
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, locationTime_GPS, locationDistance_GPS, androidLocation);
                    EnvApplication.getApplication().locationModuleTag=GlobClass.LocationModule_GPS_CODE;
                    //添加卫星状态改变监听
                    locationManager.addGpsStatusListener(gpsStatusListener);
                }else{
                    EnvLog.i("updateGpsSetting aMapLocationServer");
                    aMapLocationServer.startLocation();
                    ToastUtil.showShort(mContext,"当前为网络定位！");
                    EnvApplication.getApplication().locationModuleTag= LocationModule_NetWork_CODE;
                    EnvApplication.getApplication().firstChangeModue=1;
                    stopAndroidLocation();
                }
                getLocationInfo();
            }
        }else{
            AlertUtil.createDialog(mContext,"友情提示","系统未授权定位服务！");
        }
    }

    public void start() {
        EnvLog.i("start");
        //此处的判定是主要问题，API23之后需要先判断之后才能调用locationManager中的方法包括这里的getLastKnewnLocation方法和requestLocationUpdates方法
        if(ContextCompat.checkSelfPermission(mContext,android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
            if(locationManager!=null && androidLocation!=null){
                if(PhoneStateUtil.isGpsProviderEnabled(mContext)){
                    EnvLog.i("GpsProvider");
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, locationTime_GPS, locationDistance_GPS, androidLocation);
                    EnvApplication.getApplication().locationModuleTag=GlobClass.LocationModule_GPS_CODE;
                    //添加卫星状态改变监听
                    locationManager.addGpsStatusListener(gpsStatusListener);
                }else{
                    EnvLog.i("GpsProvider is not");
                    AlertDialog.Builder dialog = new AlertDialog.Builder((MainActivity)mContext);
                    dialog.setTitle("友情提示");
                    dialog.setMessage("GPS定位服务未开启，开启GPS服务定位更精确！");
                    dialog.setPositiveButton("设置", new android.content.DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            EnvLog.i("set gps");
                            // 转到手机设置界面，用户设置GPS
                            SystemSettingUtil.setGPSOpen(mContext);

                        }
                    });
                    dialog.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            arg0.dismiss();
                            EnvLog.i("GpsProvider is not & amap");
                            aMapLocationServer.startLocation();
                            ToastUtil.showShort(mContext,"当前为网络定位！");
                            EnvApplication.getApplication().locationModuleTag= LocationModule_NetWork_CODE;
                            EnvApplication.getApplication().firstChangeModue=1;
                            stopAndroidLocation();
                        }
                    });
                    dialog.show();
                }
            }
        }else{
            AlertUtil.createDialog(mContext,"友情提示","系统未授权定位服务！");
        }
        EnvLog.i("end start");
    }

    private GeographicLocation getLocation(){
        EnvLog.i("getLocation");
        flag=0;
        switch (EnvApplication.getApplication().locationModuleTag){
            case GlobClass.LocationModule_GPS_CODE:
                if(null==EnvApplication.getApplication().geographicLocation){
                    if(ContextCompat.checkSelfPermission(mContext,android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                        if(PhoneStateUtil.isGpsProviderEnabled(mContext)){
                            EnvLog.i("getLocation lastLocation is null & gps");
                            Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if(null==location){
                                EnvLog.i("LocationModule_GPS_CODE null==location");
                                stopAndroidLocation();
                                aMapLocationServer.startLocation();
                                EnvApplication.getApplication().locationModuleTag= LocationModule_NetWork_CODE;
                                EnvApplication.getApplication().firstChangeModue=1;
                            }else{
                                EnvLog.i("LocationModule_GPS_CODE null!=location");
                                EnvApplication.getApplication().geographicLocation= LocationConverter.androdiToGeographicLocation(mContext,location,EnvApplication.getApplication().geographicLocation);
                            }
                        }else{
                            EnvLog.i("LocationModule_GPS_CODE gps not start");
                            stopAndroidLocation();
                            aMapLocationServer.startLocation();
                            EnvApplication.getApplication().locationModuleTag= LocationModule_NetWork_CODE;
                            EnvApplication.getApplication().firstChangeModue=1;
                        }
                    }else{
                        flag=1;
                    }
                }
                break;
            case LocationModule_NetWork_CODE:
                if(null==EnvApplication.getApplication().geographicLocation){
                    if(ContextCompat.checkSelfPermission(mContext,android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
                        if(PhoneStateUtil.isGpsProviderEnabled(mContext)){
                            EnvLog.i("LocationModule_NetWork_CODE lastLocation is null & gps");
                            stopAMapLocation();
                            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, locationTime_GPS, locationDistance_GPS, androidLocation);
                            EnvApplication.getApplication().locationModuleTag=GlobClass.LocationModule_GPS_CODE;
                            //添加卫星状态改变监听
                            locationManager.addGpsStatusListener(gpsStatusListener);
                            Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if(null==EnvApplication.getApplication().geographicLocation && null!=location){
                                EnvLog.i("LocationModule_NetWork_CODE null!=location");
                                EnvApplication.getApplication().geographicLocation= LocationConverter.androdiToGeographicLocation(mContext,location,EnvApplication.getApplication().geographicLocation);
                            }
                        }
                    }else{
                        flag=1;
                    }
                }
                break;
            default:
                EnvLog.i("LocationModule is null......");
                EnvApplication.getApplication().geographicLocation=null;
                start();
                break;
        }
        return EnvApplication.getApplication().geographicLocation;
    }

    public void stop() {
        EnvLog.i("stopLocationInfo");
        EnvApplication.getApplication().locationModuleTag=0;
        stopAndroidLocation();
        stopAMapLocation();
    }

    private void stopAndroidLocation(){
        if(ContextCompat.checkSelfPermission(mContext,android.Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED) {
            if(locationManager!=null && androidLocation!=null){
                locationManager.removeUpdates(androidLocation);
                locationManager.removeGpsStatusListener(gpsStatusListener);
            }
        }
    }
    private void stopAMapLocation(){
        if(aMapLocationServer!=null){
            aMapLocationServer.stopLocation();
        }
    }

    public void getLocationModule(){
        if(EnvApplication.getApplication().locationModuleTag==0){
            start();
        }
        getLocationInfo();
    }

    public void convertGeographicLocation(GeographicLocation geographicLocation){
        EnvLog.i("convertGeographicLocation...");
        BaseLocation baseLocation=new BaseLocation(geographicLocation.getLongitude(),geographicLocation.getLatitude());
        Gson gson=new Gson();
        String mess=gson.toJson(baseLocation);
        EnvLog.i("location mess="+mess);
        ((MainActivity)mContext).responseLocInfo(mess);
    }
    public void getLocationInfo(){
        EnvLog.i("getLocationInfo....");
        GeographicLocation geographicLocation=getLocation();
       if(flag==1){
           AlertUtil.createDialog(mContext,"友情提示","系统未授权定位服务！");
       }else{
           if(null != geographicLocation){
               convertGeographicLocation(geographicLocation);
           }else{
               EnvLog.i("null != geographicLocation......");
               if(GlobClass.LocationModule_NetWork_CODE==EnvApplication.getApplication().locationModuleTag && EnvApplication.getApplication().firstChangeModue==1){
                   EnvLog.i("....LocationModule_NetWork_CODE.....");
               }else{
                   AlertUtil.createDialog(mContext,"友情提示","定位服务信号弱,未能获取定位服务，请重试！");
               }
           }
       }
    }
    public void destroyLocation(){
        stop();
        EnvLog.i("destroyLocation....");
        aMapLocationServer.destroyLocation();
    }
    private GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener() {
        @Override
        public void onGpsStatusChanged(int event) {
            EnvLog.i("onGpsStatusChanged");
            // GPS状态变化时的回调，如卫星数
            switch (event) {
                //卫星状态改变
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    //获取当前状态
                    GpsStatus gpsStatus = locationManager.getGpsStatus(null);
                    //获取卫星颗数的默认最大值
                    int maxSatellites = gpsStatus.getMaxSatellites();
                    //获取所有的卫星
                    Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
                    //卫星颗数统计
                    int count = 0;
                    while (iters.hasNext() && count <= maxSatellites) {

                        GpsSatellite s = iters.next();
                        //卫星的信噪比
                        //float snr = s.getSnr();

                        if(s.usedInFix()){
                            count++;
                        }
                        //只有信躁比不为0的时候才算有效星数
                        /*if(s.getSnr()!=0){
                            count++;
                        }*/
                    }
                    EnvLog.i("count="+count);
                    if(count<=4){
                        EnvLog.i("太少了");
                        stopAndroidLocation();
                        aMapLocationServer.startLocation();
                        EnvApplication.getApplication().locationModuleTag= LocationModule_NetWork_CODE;
                        EnvApplication.getApplication().firstChangeModue=1;
                    }
                    break;
                default:
                    break;
            }
        }
    };
}
